class SearchManager {
    constructor() {
        this.searchInput = document.getElementById('search-input-id');
        this.searchButton = document.getElementById('search-enter');
        this.searchResult = document.getElementById('search-result');
        this.searchResultNone = document.getElementById('search-result-none');
        this.addFriendButton = document.getElementById('search-result-add-friend-btn');
        this.currentUserId = null;
        this.userName = null;
        this.searchResultType = '';
        
        this.initializeEvents();
        this.hideResults();
        this.initializeUser();
    }

    initializeEvents() {
        // 搜索按钮点击事件
        this.searchButton.addEventListener('click', () => this.handleSearch());
        
        // 输入框回车事件
        this.searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.handleSearch();
            }
        });
        
        // 添加好友按钮点击事件
        this.addFriendButton.addEventListener('click', () => this.handleAddFriend());
    }

    hideResults() {
        this.searchResult.classList.add('hide');
        this.searchResultNone.classList.add('hide');
    }

    showNoResult() {
        this.searchResult.classList.add('hide');
        this.searchResultNone.classList.remove('hide');
    }

    showResult(data) {
        this.searchResult.classList.remove('hide');
        this.searchResultNone.classList.add('hide');
        
        // 更新搜索结果显示，处理字符串 "null" 的情况
        const displayName = (data.name && data.name !== 'null') ? data.name : '未知用户';
        document.getElementById('search-result-username').textContent = displayName;
        document.getElementById('search-result-id').textContent = this.searchInput.value;
        
        // 根据类型更新显示
        const typeLabel = document.getElementById('search-result-type-label');
        const addButton = document.getElementById('search-result-add-friend-btn');
        const avatar = document.querySelector('.search-result-item svg circle');
        
        // 重置按钮状态
        addButton.disabled = false;
        addButton.classList.remove('btn-success');
        addButton.classList.add('btn-outline-primary');
        
        if (data.type === 'group') {
            typeLabel.textContent = '群组名称:';
            addButton.textContent = '加入群组';
            avatar.setAttribute('fill', 'rgb(0, 153, 255)');
            this.searchResultType = 'group';
        } else {
            typeLabel.textContent = '用户名:';
            addButton.textContent = '添加好友';
            avatar.setAttribute('fill', 'rgb(0,0,139)');
            this.searchResultType = 'user';
        }
    }

    validateInput(id) {
        // 检查输入是否为空
        if (!id.trim()) {
            alert('请输入要搜索的ID');
            return false;
        }
        
        // 检查输入是否为数字
        if (!/^\d+$/.test(id)) {
            alert('ID必须是数字');
            return false;
        }
        
        return true;
    }

    async handleSearch() {
        const searchId = this.searchInput.value.trim();
        
        // 输入验证
        if (!this.validateInput(searchId)) {
            return;
        }

        try {
            // 禁用搜索按钮，显示加载状态
            this.searchButton.disabled = true;
            this.searchButton.innerHTML = `
                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
            `;

            const response = await fetch(`http://${_HOST_}:${_PORT_}/GetName`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    Id: searchId
                })
            });

            const data = await response.json();

            switch (data.code) {
                case '0000':
                    if (!data.name) {
                        this.showNoResult();
                        return;
                    }
                    this.showResult(data);
                    break;
                case '1010':
                    this.showNoResult();
                    break;
                case '1003':
                    alert('服务器内部错误，请稍后重试');
                    this.hideResults();
                    break;
                case '2000':
                    alert('发生未知错误，请稍后重试');
                    this.hideResults();
                    break;
                default:
                    alert(`搜索失败：${data.msg}`);
                    this.hideResults();
            }
        } catch (error) {
            console.error('搜索失败:', error);
            alert('网络错误，请检查网络连接后重试');
            this.hideResults();
        } finally {
            // 确保一定会重置搜索按钮状态
            this.searchButton.disabled = false;
            this.searchButton.innerHTML = `
                <svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" width="32" height="32">
                    <path fill="#1a1a1a" fill-rule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8"></path>
                </svg>
            `;
        }
    }

    async handleAddFriend() {
        if (!this.currentUserId) {
            alert('请先登录');
            return;
        }

        const targetId = document.getElementById('search-result-id').textContent;
        
        // 添加自我检查逻辑
        if (this.searchResultType === 'user' && targetId === this.currentUserId) {
            alert('不能添加自己为好友');
            return;
        }

        try {
            this.addFriendButton.disabled = true;
            this.addFriendButton.innerHTML = `
                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                正在处理...
            `;

            let url, requestBody;
            
            if (this.searchResultType === 'user') {
                url = `http://${_HOST_}:${_PORT_}/BuildFriend`;
                requestBody = {
                    userId: this.currentUserId,
                    friendId: targetId
                };
            } else {
                url = `http://${_HOST_}:${_PORT_}/EnterGroup`;
                requestBody = {
                    userId: this.currentUserId,
                    groupId: targetId
                };
            }

            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestBody)
            });

            const data = await response.json();

            if (this.searchResultType === 'user') {
                // 处理添加好友的响应
                switch (data.code) {
                    case '0000':
                        this.addFriendButton.classList.add('btn-success');
                        this.addFriendButton.classList.remove('btn-outline-primary');
                        this.addFriendButton.textContent = '添加成功';
                        this.addFriendButton.disabled = true;
                        break;
                    case '1009':
                        alert('添加好友失败，请稍后重试');
                        this.addFriendButton.disabled = false;
                        this.addFriendButton.textContent = '添加好友';
                        break;
                    case '1003':
                        alert('服务器内部错误，请稍后重试');
                        break;
                    default:
                        alert(data.msg || '未知错误');
                }
            } else {
                // 处理加入群组的响应
                switch (data.code) {
                    case '0000':
                        this.addFriendButton.classList.add('btn-success');
                        this.addFriendButton.classList.remove('btn-outline-primary');
                        this.addFriendButton.textContent = '加入成功';
                        this.addFriendButton.disabled = true;
                        break;
                    case '1004':
                        alert('用户ID不存在，请重新登');
                        break;
                    case '1008':
                        alert('群组ID不存在');
                        break;
                    case '1002':
                        alert('参数不合法，请检查输入');
                        break;
                    case '1003':
                        alert('服务器内部错误，请稍后重试');
                        break;
                    default:
                        alert(data.msg || '未知错误');
                }
            }
        } catch (error) {
            console.error('操作失败:', error);
            alert('网络错误，请检查网络连接后重试');
            this.addFriendButton.disabled = false;
            this.addFriendButton.textContent = this.searchResultType === 'user' ? '添加好友' : '加入群组';
        }
    }

    async initializeUser() {
        try {
            const userData = await window.clickBtn.getUserDataObject();
            this.currentUserId = userData.userId;
            this.userName = userData.userName;
            console.log('用户数据初始化成功:', { id: this.currentUserId, name: this.userName });
        } catch (error) {
            console.error('初始化用户数据失败:', error);
            alert('获取用户信息失败，请重新登录');
        }
    }
}

// 初始化搜索管理器
document.addEventListener('DOMContentLoaded', () => {
    const searchManager = new SearchManager();
});